package wind

import (
	"database/sql"
	"sync"

	"gitee.com/tinkler/yunfei/ws/arsenal"
	"gitee.com/tinkler/yunfei/ws/forge"
	"golang.org/x/text/language"
	"golang.org/x/text/message"
)

type Sheath struct {
	memMu sync.RWMutex
	mem   forge.MemDB
	db    *sql.DB
	c     *SheathConf
}

type SheathConf struct {
	Lang string
}

func (s Sheath) SetLang(lang string) {
	s.c.Lang = lang
}

func (s Sheath) CloseDB() {
	s.db.Close()
}

func (s Sheath) GetDB() *sql.DB {
	return s.db
}

func (s Sheath) setStore(name string) {
	s.memMu.Lock()
	defer s.memMu.Unlock()
	if name == "" {
		panic("ws: Store name is empty")
	}
	if _, dup := s.mem[name]; dup {
		return
	}
	store := make(forge.MemStore)
	s.mem[name] = store
}

func (s Sheath) Use(name string) arsenal.Sleeve {
	var sl Sleeve
	sl.db = s.db
	sl.storeMu.Lock()
	defer sl.storeMu.Unlock()
	s.setStore(name)
	sl.store = s.mem[name]

	if s.c.Lang != "" {
		tag := language.Make(s.c.Lang)
		sl.p = message.NewPrinter(tag)
	} else {
		sl.p = message.NewPrinter(language.Chinese)
	}

	return &sl
}
